/*
1.在引入该js文件前，需要先引入dat.gui.js文件
2.option={
    groups:[
        {
            name:"F3-6",
            data:["F3","F6"]
        },
        {
            name:"F21-26",
            data:["F21","F26"]
        }
     ],  //分组名，用来对应选择当前的name
     name:["cube1","cube2","group"],   //对象名称，用来识别对象和作为保存加载ID
     material:[cubeMaterial1,cubeMaterial2,groupMaterial],   //对象材质
     object:[cubeMesh1,cubeMesh2,group],  //对象
     scene:scene,  //场景
     light:[spotLight,AmbientLight],  //光照
     renderer:renderer
}
3.导入的json材质文件应放在mtl中
*/
var WEBUILDING = new function(){
    this.DefaultMaterial = "default/";
    this.NormalMaterial = "normal/";
}
function webuilding(option) {
    //var _option = option;
    var urlHead = "static/mtl/";
    var urlMaterial = WEBUILDING.DefaultMaterial ;
    var _option = loadJson(option);
    //重新设置所有参数
    this.setOption=function (option) {
        _option=option;
        updateControls();
    }
    //初始化设置
    this.initalLoading = function(MatiralType){
        _option = loadJson(option,MatiralType);
        _option.object[78]=null;  //将鼠标拾取值设为null
        updateControls();
    }
    //修改单个参数，暂时只支持修改option.Object属性
    this.updateOption=function (index,object,material) {
        if (object instanceof THREE.Mesh){
            _option.material[index]=material;
            _option.object[index]=object;
            //_option.object[index].material=_option.material[index];  
        }else {
            console.log("错误>>暂不支持更改该对象！")
        }
    }

    var meshIndex=0;  //mesh索引

    var spotLigthIndex,ambientLightIndex,directionalLightIndex,pointLigthIndex,HemisphereLigthIndex;  //光源索引
    var AmbientLight_Gui,PointLight_Gui,SpotLight_Gui,DirectionalLight_Gui,HemisphereLight_Gui;  //光源组 
    if (_option.name.length>_option.object.length){
        console.log('error>>mesh.name.length>_option.material.length');
        return;
    }
    //雾化
    var fogEnable,fogColor,fogNear,fogFar;
    if (_option.scene.fog){
        fogEnable=true;
        fogColor=_option.scene.fog.color.getStyle();
        fogNear=_option.scene.fog.near;
        fogFar=_option.scene.fog.far;
    }else{
        fogEnable=false;
        fogColor=new THREE.Color(0xffffff).getStyle();
        fogNear=50;
        fogFar=500;
    }

    //dat属性
    var controls={
        select:"",
        mesh:_option.name[meshIndex],
        material:"", //材质
        transparent:false, //是否透明 Boolean
        opacity:1,  //不透明度 0.0-1.0 float
        visible:true, //是否可见 Boolean
        side:"front",  //侧面 THREE.FrontSide：前面，THREE.BackSide:后面，THREE.DoubleSide：双侧
        color:new THREE.Color(0xffffff).getStyle(),
        wireframe:false,   //是否显示线框
        wireframeLinewidth:1,  //线框宽度
        //emissive:new THREE.Color(0x000000).getStyle(),   //发射光
        specular:new THREE.Color(0x111111 ).getHex(),
        shininess:30,  //镜面高光部分的亮度
        blending:"No",   //混合
        premultipliedAlpha:false,  //是否预先乘以alpha（透明度）值
        linewidth:1,
        fogEnable:fogEnable,  //场景雾化效果
        fogColor:fogColor,  //雾化颜色
        fogNear:fogNear,  //雾化近处
        fogFar:fogFar,  //雾化远处
        rendererColor:new THREE.Color(0xeeeeee).getStyle(),  //背景色
        materialSave:function () { //保存材质
            var cube_save=new THREE.Mesh(new THREE.BoxGeometry(1,1,1),_option.material[meshIndex]);
            var result=cube_save.toJSON();
            saveString( JSON.stringify(result), _option.name[meshIndex]+'.json' );
        },
        materialSaveAll:function () { //保存材质
            console.log(_option.material.length)
            for (var i=0;i<_option.material.length;i++){
                var cube_save=new THREE.Mesh(new THREE.BoxGeometry(1,1,1),_option.material[i]);
                var result=cube_save.toJSON();
                saveString( JSON.stringify(result), _option.name[i]+'.json' );
            }
        },
        materialLoad:function () {  //加载材质
            var url =  urlHead + urlMaterial +_option.name[meshIndex]+".json";
            $.getJSON(url,function (data,status) {
                if (status=="success"){
                    // var loadedGeometry = JSON.parse(data);
                    var loader = new THREE.ObjectLoader();
                    var loadedMesh = loader.parse(data);
                    _option.material[meshIndex]=loadedMesh.material;
                    if(_option.object[meshIndex] instanceof THREE.Group){
                        _option.object[meshIndex].traverse(function (child) {
                            child.material=_option.material[meshIndex];
                        })
                    }else{
                        _option.object[meshIndex].material=_option.material[meshIndex];
                    }
                    console.log("成功导入 "+_option.name[meshIndex]+"材质！");
                    updateControls();

                }else {
                    console.log(status);
                }
            });
        },
        fogSave:function () {  //保存雾化
            var result={
                fogEnable:controls.fogEnable,  //场景雾化效果
                fogColor:controls.fogColor,  //雾化颜色
                fogNear:controls.fogNear,  //雾化近处
                fogFar:controls.fogFar  //雾化远处
            };
            saveString( JSON.stringify(result), 'sceneFog.json' );
            console.log("成功保存雾化参数！");
        },
        fogLoad:function () {  //加载雾化
            var url= urlHead + urlMaterial +"sceneFog.json";
            $.getJSON(url,function (data,status) {
                if (status=="success"){
                    if (data.fogEnable){
                        _option.scene.fog=new THREE.Fog(data.fogColor,data.fogNear,data.fogFar);
                    }else {
                        _option.scene.fog=null;
                    }
                    console.log("成功加载雾化效果!");
                    updateControls();

                }else {
                    console.log(status);
                }
            });
        },
        record:function(){
            console.log("相机位置记录  x:"+_option.camera.position.x+",y:"+_option.camera.position.y+",z:"+_option.camera.position.z);
        },
        rendererSave:function () {
            var result={
                color:controls.rendererColor
            };
            saveString( JSON.stringify(result), 'rendererColor.json' );
            console.log("成功保存背景颜色参数！");
        },
        rendererLoad:function () {
            var url= urlHead + urlMaterial + "renderer.json";
            $.getJSON(url,function (data,status) {
                if (status=="success"){
                    _option.renderer.setClearColor(renderer.color);
                    console.log("成功加载背景颜色!");
                    updateControls();

                }else {
                    console.log(status);
                }
            });
        }

    };


    var gui=new dat.GUI();
    var objects_Gui = gui.addFolder("objects");
    for (var i=0;i<_option.groups.length;i++){
        var group = objects_Gui.addFolder(_option.groups[i].name);
        group.add(controls,"select",_option.groups[i].data).onChange(function (e) {
            controls.mesh=e;
            meshIndex=_option.name.indexOf(e);
            updateControls();
        })
    }
    //选择对象
    objects_Gui.add(controls,"mesh",_option.name).onChange(function (e) {
        meshIndex=_option.name.indexOf(e);
        updateControls();
    });

    //选择材质
    objects_Gui.add(controls,"material",["Basic","Depth","Normal","Lambert","Phong","LineBasic"]).onChange(function (e) {
        var material;
        switch (e) {
            case "Basic":
                material=new THREE.MeshBasicMaterial({side:THREE.FrontSide});
                break;
            case "Depth":
                material=new THREE.MeshDepthMaterial({side:THREE.FrontSide});
                break;
            case "Normal":
                material=new THREE.MeshNormalMaterial({side:THREE.FrontSide});
                break;
            case "Lambert":
                material=new THREE.MeshLambertMaterial({side:THREE.FrontSide});
                break;
            case "Phong":
                material=new THREE.MeshPhongMaterial({side:THREE.FrontSide});
                break;
            case "LineBasic":
                material=new THREE.LineBasicMaterial();
                break;
        }
        if(_option.object[meshIndex] instanceof THREE.Group){
            _option.object[meshIndex].traverse(function (child) {
                child.material=material;
            })
        }else{
            _option.object[meshIndex].material=material;//bug  也不一定都是Group节点
        }
        _option.material[meshIndex]=material;
        _option.material[meshIndex].needsUpdate = true;
        updateControls();


    });

    //通用材质属性
    var generalMat_Gui=objects_Gui.addFolder("General Material");
    var item=generalMat_Gui.add(controls,"transparent").onChange(function (e) {
        _option.material[meshIndex].transparent=e;
    });
    generalMat_Gui.add(controls,"opacity",0,1).onChange(function (e) {
        _option.material[meshIndex].opacity=e;
    });
    generalMat_Gui.add(controls,"visible").onChange(function (e) {
        _option.material[meshIndex].visible=e;
    });
    generalMat_Gui.add(controls,"premultipliedAlpha").onChange(function (e) {
        _option.material[meshIndex].premultipliedAlpha=e;
    });
    generalMat_Gui.addColor(controls,"color").onChange(function (e) {
        if (controls.material=="Depth" || controls.material=="Normal"){
            console.log("错误>>"+controls.material+"材质没有color属性");
            return;
        }
        _option.material[meshIndex].color.set(e);
        var material=_option.material[meshIndex];
        if(_option.name[meshIndex]!="selecting"){
            if(_option.object[meshIndex] instanceof THREE.Group){
                _option.object[meshIndex].traverse(function (child) {
                    child.material=material;
                })
            }else if (_option.object[meshIndex] instanceof THREE.Mesh){
                _option.object[meshIndex].material=material;
            }else {
                console.log("错误>>第 "+(meshIndex+1)+" object 对象为null");
                return;
            }
        }
        
        _option.material[meshIndex]=material;
        _option.material[meshIndex].needsUpdate = true;
    });
    generalMat_Gui.add(controls,"wireframe").onChange(function (e) {
        _option.material[meshIndex].wireframe=e;
    });
    generalMat_Gui.add(controls,"wireframeLinewidth",0,10).onChange(function (e) {
        _option.material[meshIndex].wireframeLinewidth=e;
    });
    //侧面
    generalMat_Gui.add(controls,"side",["front", "back", "double"]).onChange(function (e) {
        switch (e) {
            case "front":
                _option.material[meshIndex].side = THREE.FrontSide;
                break;
            case "back":
                _option.material[meshIndex].side = THREE.BackSide;
                break;
            case "double":
                _option.material[meshIndex].side = THREE.DoubleSide;
                break;
        }
        _option.material[meshIndex].needsUpdate = true;
    });
    generalMat_Gui.add(controls,"blending",["No", "Normal", "Additive","Subtractive","Multiply","Custom"]).onChange(function (e) {
        switch (e) {
            case "No":
                _option.material[meshIndex].blending = THREE.NoBlending;
                break;
            case "Normal":
                _option.material[meshIndex].blending = THREE.NormalBlending;
                break;
            case "Additive":
                _option.material[meshIndex].blending = THREE.AdditiveBlending;
                break;
            case "Subtractive":
                _option.material[meshIndex].blending = THREE.SubtractiveBlending;
                break;
            case "Multiply":
                _option.material[meshIndex].blending = THREE.MultiplyBlending;
                break;
            case "Custom":
                _option.material[meshIndex].blending = THREE.CustomBlending;
                break;
        }
        _option.material[meshIndex].needsUpdate = true;
    });
    //MeshBasicMaterial
    var BasicMat_Gui=objects_Gui.addFolder("MeshBasicMaterial");

    var DepthMat_Gui=objects_Gui.addFolder("MeshDepthMaterial");

    var NormalMat_Gui=objects_Gui.addFolder("MeshNormalMaterial");

    var LambertMat_Gui=objects_Gui.addFolder("MeshLambertMaterial");

    // LambertMat_Gui.addColor(controls,"emissive").onChange(function (e) {
    //     if (!IsEnable("Lambert")){
    //         return;
    //     };
    //     _option.material[meshIndex].emissive.set(e);
    // });
    var PhongMat_Gui=objects_Gui.addFolder("MeshPhongMaterial");

    // PhongMat_Gui.addColor(controls,"emissive").onChange(function (e) {
    //     console.log("emissive11")
    //     if (!IsEnable("Phong")){
    //         return;
    //     };
    //     _option.material[meshIndex].emissive.set(e);
    //     _option.material[meshIndex].needsUpdate=true;
    //     console.log("emissive")
    // });
    PhongMat_Gui.addColor(controls,"specular").onChange(function (e) {
        _option.material[meshIndex].specular.set(e);
        _option.material[meshIndex].needsUpdate=true;
    });
    PhongMat_Gui.add(controls,"shininess",0,60).onChange(function (e) {
        if (!IsEnable("Phong")){
            return;
        };
        _option.material[meshIndex].shininess = e;
        _option.material[meshIndex].needsUpdate=true;
    });
    var LineBasicMat_Gui=objects_Gui.addFolder("LineBasicMaterial");
    LineBasicMat_Gui.add(controls,"linewidth",0,10).onChange(function (e) {
        _option.material[meshIndex].linewidth=e;
    });

    objects_Gui.add(controls,"materialSave");
    objects_Gui.add(controls,"materialSaveAll");
    objects_Gui.add(controls,"materialLoad");


    //dat初始化光源
    for (var i=0;i<_option.light.length;i++){
        if (_option.light[i] instanceof THREE.AmbientLight){
            ambientLightIndex=i;
            controls["ALVisible"]=_option.light[i].visible;
            controls["AmbientLightColor"]=_option.light[i].color.getStyle();
            controls["ALIntensity"]=_option.light[i].intensity;
            controls["ALSave"]=function () {
                var result={
                    AmbientLightColor:controls.AmbientLightColor,
                    visible:controls.ALVisible,
                    intensity:controls.ALIntensity
                }
                saveString( JSON.stringify(result), 'AmbientLight.json' );
                console.log("成功保存AmbientLight参数！");
            };
            controls["ALLoad"]=function () {
                var url= urlHead + urlMaterial + "AmbientLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        _option.light[ambientLightIndex].color.set(data.AmbientLightColor);
                        _option.light[ambientLightIndex].visible=data.visible;
                        _option.light[ambientLightIndex].intensity=data.intensity;
                        console.log("成功加载AmbientLight效果!");
                        updateControls();

                    }else {
                        console.log(status);
                    }
                });
            };
            AmbientLight_Gui=gui.addFolder("AmbientLight");
            AmbientLight_Gui.add(controls,"ALVisible").onChange(function (e) {
                _option.light[ambientLightIndex].visible=e;
            });
            AmbientLight_Gui.addColor(controls,"AmbientLightColor").onChange(function (e) {
                _option.light[ambientLightIndex].color.set(e);
            });
            AmbientLight_Gui.add(controls,"ALIntensity",1,10).onChange(function (e) {
                _option.light[ambientLightIndex].intensity=e;
            });
            AmbientLight_Gui.add(controls,"ALSave");
            AmbientLight_Gui.add(controls,"ALLoad");
        }else if (_option.light[i] instanceof THREE.PointLight){
            pointLigthIndex=i;
            controls["PLVisible"]=_option.light[i].visible;
            controls["PointLightColor"]=_option.light[i].color.getStyle();
            controls["PLIntensity"]=_option.light[i].intensity;
            controls["PLPositionX"]=_option.light[i].position.x;
            controls["PLPositionY"]=_option.light[i].position.y;
            controls["PLPositionZ"]=_option.light[i].position.z;
            controls["PLSave"]=function () {
                var result={
                    visible:controls.PLVisible,
                    color:controls.SpotLightColor,
                    positionX:controls.PLPositionX,
                    positionY:controls.PLPositionY,
                    positionZ:controls.PLPositionZ,
                    intensity:controls.PLIntensity
                };
                saveString( JSON.stringify(result), 'PointLight.json' );
                console.log("成功保存PointLight参数！");
            };
            controls["PLLoad"]=function () {
                var url= urlHead + urlMaterial + "PointLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        _option.light[pointLigthIndex].color.set(data.color);
                        _option.light[pointLigthIndex].intensity=data.intensity;
                        _option.light[pointLigthIndex].visible=data.visible;
                        _option.light[pointLigthIndex].position.x=data.positionX;
                        _option.light[pointLigthIndex].position.y=data.positionY;
                        _option.light[pointLigthIndex].position.z=data.positionZ;
                        console.log("成功加载PointLight效果!");
                        updateControls();

                    }else {
                        console.log(status);
                    }
                });
            };

            PointLight_Gui=gui.addFolder("PointLight");
            PointLight_Gui.add(controls,"PLVisible").onChange(function (e) {
                _option.light[pointLigthIndex].visible=e;
            });
            PointLight_Gui.addColor(controls,"PointLightColor").onChange(function (e) {
                _option.light[pointLigthIndex].color.set(e);
            });
            PointLight_Gui.add(controls,"PLIntensity",1,10).onChange(function (e) {
                _option.light[pointLigthIndex].intensity=e;
            });
            PointLight_Gui.add(controls,"PLPositionX",-2000,2000).onChange(function (e) {
                _option.light[pointLigthIndex].position.x=e;
            });
            PointLight_Gui.add(controls,"PLPositionY",-2000,2000).onChange(function (e) {
                _option.light[pointLigthIndex].position.y=e;
            });
            PointLight_Gui.add(controls,"PLPositionZ",-2000,2000).onChange(function (e) {
                _option.light[pointLigthIndex].position.z=e;
            });
            PointLight_Gui.add(controls,"PLSave");
            PointLight_Gui.add(controls,"PLLoad");
        }else if (_option.light[i] instanceof THREE.SpotLight){
            spotLigthIndex=i;
            controls["SLVisible"]=_option.light[i].visible;
            controls["SpotLightColor"]=_option.light[i].color.getStyle();
            controls["SLIntensity"]=_option.light[i].intensity;
            controls["SLPositionX"]=_option.light[i].position.x;
            controls["SLPositionY"]=_option.light[i].position.y;
            controls["SLPositionZ"]=_option.light[i].position.z;
            controls["SLSave"]=function () {
                var result={
                    SLVisible:controls.SLVisible,
                    SpotLightColor:controls.SpotLightColor,
                    SLPositionX:controls.SLPositionX,
                    SLPositionY:controls.SLPositionY,
                    SLPositionZ:controls.SLPositionZ,
                    intensity:controls.SLIntensity
                };
                saveString( JSON.stringify(result), 'SpotLight.json' );
                console.log("成功保存SpotLight参数！");
            };
            controls["SLLoad"]=function () {
                var url= urlHead + urlMaterial + "SpotLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        _option.light[spotLigthIndex].color.set(data.SpotLightColor);
                        _option.light[spotLigthIndex].intensity=data.intensity;
                        _option.light[spotLigthIndex].visible=data.SLVisable;
                        _option.light[spotLigthIndex].position.x=data.SLPositionX;
                        _option.light[spotLigthIndex].position.y=data.SLPositionY;
                        _option.light[spotLigthIndex].position.z=data.SLPositionZ;
                        console.log("成功加载SpotLight效果!");
                        updateControls();

                    }else {
                        console.log(status);
                    }
                });
            };

            SpotLight_Gui=gui.addFolder("SpotLight");
            SpotLight_Gui.add(controls,"SLVisible").onChange(function (e) {
                _option.light[spotLigthIndex].visible=e;
            });
            SpotLight_Gui.addColor(controls,"SpotLightColor").onChange(function (e) {
                _option.light[spotLigthIndex].color.set(e);
            });
            SpotLight_Gui.add(controls,"SLIntensity",1,10).onChange(function (e) {
                _option.light[spotLigthIndex].intensity=e;
            });
            SpotLight_Gui.add(controls,"SLPositionX",-2000,2000).onChange(function (e) {
                _option.light[spotLigthIndex].position.x=e;
            });
            SpotLight_Gui.add(controls,"SLPositionY",-2000,2000).onChange(function (e) {
                _option.light[spotLigthIndex].position.y=e;
            });
            SpotLight_Gui.add(controls,"SLPositionZ",-2000,2000).onChange(function (e) {
                _option.light[spotLigthIndex].position.z=e;
            });
            SpotLight_Gui.add(controls,"SLSave");
            SpotLight_Gui.add(controls,"SLLoad");
        }else if (_option.light[i] instanceof THREE.DirectionalLight){
            directionalLightIndex=i;
            controls["DLVisible"]=_option.light[i].visible;
            controls["DLIntensity"]=_option.light[i].intensity;
            controls["DLightColor"]=_option.light[i].color.getStyle();
            controls["DLPositionX"]=_option.light[i].position.x;
            controls["DLPositionY"]=_option.light[i].position.y;
            controls["DLPositionZ"]=_option.light[i].position.z;
            controls["DLSave"]=function () {
                var result={
                    DLVisible:controls.DLVisible,
                    DLightColor:controls.DLightColor,
                    DLPositionX:controls.DLPositionX,
                    DLPositionY:controls.DLPositionY,
                    DLPositionZ:controls.DLPositionZ,
                    intensity:intensity
                };
                saveString( JSON.stringify(result), 'DirectionalLight.json' );
                console.log("成功保存DirectionalLight参数！");
            };
            controls["DLLoad"]=function () {
                var url= urlHead + urlMaterial + "DirectionalLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        _option.light[directionalLightIndex].color.set(data.DLightColor);
                        _option.light[directionalLightIndex].intensity=data.intensity;
                        _option.light[directionalLightIndex].visible=data.DLVisible;
                        _option.light[directionalLightIndex].position.x=data.DLPositionX;
                        _option.light[directionalLightIndex].position.y=data.DLPositionY;
                        _option.light[directionalLightIndex].position.z=data.DLPositionZ;
                        console.log("成功加载DirectionalLight效果!");
                        updateControls();

                    }else {
                        console.log(status);
                    }
                });
            };
            DirectionalLight_Gui=gui.addFolder("DirectionalLight");
            DirectionalLight_Gui.add(controls,"DLVisible").onChange(function (e) {
                _option.light[directionalLightIndex].visible=e;
            });
            DirectionalLight_Gui.addColor(controls,"DLightColor").onChange(function (e) {
                _option.light[directionalLightIndex].color.set(e);
            });
            DirectionalLight_Gui.add(controls,"DLIntensity",1,10).onChange(function (e) {
                _option.light[directionalLightIndex].intensity=e;
            });
            DirectionalLight_Gui.add(controls,"DLPositionX",-2000,2000).onChange(function (e) {
                _option.light[directionalLightIndex].position.x=e;
            });
            DirectionalLight_Gui.add(controls,"DLPositionY",-2000,2000).onChange(function (e) {
                _option.light[directionalLightIndex].position.y=e;
            });
            DirectionalLight_Gui.add(controls,"DLPositionZ",-2000,2000).onChange(function (e) {
                _option.light[directionalLightIndex].position.z=e;
            });
            DirectionalLight_Gui.add(controls,"DLSave");
            DirectionalLight_Gui.add(controls,"DLLoad");
        }else if (_option.light[i] instanceof THREE.HemisphereLight){
            hemisphereLightIndex=i;
            controls["HLVisible"]=_option.light[i].visible;
            controls["HLColor"]=_option.light[i].color.getStyle();
            controls["HLGColor"]=_option.light[i].groundColor.getStyle();
            controls["HLIntensity"]=_option.light[i].intensity;
            controls["HLSave"]=function () {
                var result={
                    color:controls.HLColor,
                    groundColor:controls.HLGColor,
                    visible:controls.HLVisible,
                    intensity:controls.HLIntensity
                }
                saveString( JSON.stringify(result), 'HemisphereLight.json' );
                console.log("成功保存HemisphereLight参数！");
            };
            controls["HLLoad"]=function () {
                var url= urlHead + urlMaterial + "HemisphereLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        _option.light[hemisphereLightIndex].color.set(data.color);
                        _option.light[hemisphereLightIndex].groundColor.set(data.groundColor);
                        _option.light[hemisphereLightIndex].visible=data.visible;
                        _option.light[hemisphereLightIndex].intensity=data.intensity;
                        console.log("成功加载HemisphereLight效果!");
                        updateControls();

                    }else {
                        console.log(status);
                    }
                });
            };
            HemisphereLight_Gui=gui.addFolder("HemisphereLight");
            HemisphereLight_Gui.add(controls,"HLVisible").onChange(function (e) {
                _option.light[hemisphereLightIndex].visible=e;
            });
            HemisphereLight_Gui.addColor(controls,"HLColor").onChange(function (e) {
                _option.light[hemisphereLightIndex].color.set(e);
            });
            HemisphereLight_Gui.addColor(controls,"HLGColor").onChange(function (e) {
                _option.light[hemisphereLightIndex].groundColor.set(e);
            });
            HemisphereLight_Gui.add(controls,"HLIntensity",1,10).onChange(function (e) {
                _option.light[hemisphereLightIndex].intensity=e;
            });
            HemisphereLight_Gui.add(controls,"HLSave");
            HemisphereLight_Gui.add(controls,"HLLoad");
        }
    }

    //场景雾化
    var scene_Gui=gui.addFolder("Scene");

    scene_Gui.add(controls,"fogEnable").onChange(function (e) {
        if (e){
            _option.scene.fog=new THREE.Fog(controls.fogColor,controls.fogNear,controls.fogFar);
        }else {
            _option.scene.fog=null;
        }
    });
    scene_Gui.addColor(controls,"fogColor").onChange(function (e) {
        if (controls.fogEnable) {
            _option.scene.fog = new THREE.Fog(e, controls.fogNear, controls.fogFar);
        }
    });
    scene_Gui.add(controls,"fogNear",0,5000).onChange(function (e) {
        if (controls.fogEnable && e<controls.fogFar){
            _option.scene.fog.near=e;
        }
    });
    scene_Gui.add(controls,"fogFar",0,5000).onChange(function (e) {
        if (controls.fogEnable && controls.fogNear<e){
            _option.scene.fog.far=e;
        }
    });
    scene_Gui.add(controls,"fogSave");
    scene_Gui.add(controls,"fogLoad");


    //背景色
    var renderer_Gui=gui.addFolder("renderer color");
    renderer_Gui.addColor(controls,"rendererColor").onChange(function (e) {
        _option.renderer.setClearColor(new THREE.Color(e));
    });
    renderer_Gui.add(controls,"rendererSave");
    renderer_Gui.add(controls,"rendererLoad");

    //相机位置
    var camera_Gui = gui.addFolder("camera");
    camera_Gui.add(controls,"record");

    updateControls();




/*----------------------------------------------分割线---------------------------------------------*/

    function IsEnable(name) {
        if(controls.material!=name){
            console.log("错误>>请先选择该材质");
            return false;
        }
        return true;
    }

    //更新dat属性
    function updateControls() {
        var materialType="";
        if (_option.material[meshIndex] instanceof THREE.MeshBasicMaterial){
            controls.material="Basic";
            materialType="MeshBasicMaterial";
        }else if (_option.material[meshIndex] instanceof THREE.MeshDepthMaterial){
            controls.material="Depth";
            materialType="MeshDepthMaterial";
        }else if (_option.material[meshIndex] instanceof THREE.MeshNormalMaterial){
            controls.material="Normal";
            materialType="MeshNormalMaterial";
        }else if (_option.material[meshIndex] instanceof THREE.MeshLambertMaterial){
            controls.material="Lambert";
            materialType="MeshLambertMaterial";
        }else if (_option.material[meshIndex] instanceof THREE.MeshPhongMaterial){
            controls.material="Phong";
            materialType="MeshPhongMaterial";
        }else if (_option.material[meshIndex] instanceof THREE.LineBasicMaterial){
            controls.material="LineBasic";
            materialType="LineBasicMaterial";
        }
        controls.transparent=_option.material[meshIndex].transparent;
        controls.opacity=_option.material[meshIndex].opacity;
        controls.overdraw=_option.material[meshIndex].overdraw;
        controls.visible=_option.material[meshIndex].visible;
        controls.premultipliedAlpha=_option.material[meshIndex].premultipliedAlpha;
        switch (_option.material[meshIndex].side){
            case 0:
                controls.side="front";
                break;
            case 1:
                controls.side="back";
                break;
            case 2:
                controls.side="double";
                break;
        }

        switch (_option.material[meshIndex].blending){
            case 0:
                controls.blending="No";
                break;
            case 1:
                controls.blending="Normal";
                break;
            case 2:
                controls.blending="Additive";
                break;
            case 3:
                controls.blending="Subtractive";
                break;
            case 4:
                controls.blending="Multiply";
                break;
            case 5:
                controls.blending="Custom";
                break;
        }
        controls.wireframe=_option.material[meshIndex].wireframe;
        controls.wireframeLinewidth=_option.material[meshIndex].wireframeLinewidth;
        if (materialType!="MeshDepthMaterial" && materialType!="MeshNormalMaterial"){
            controls.color=_option.material[meshIndex].color.getStyle();
        }
        // if (materialType=="MeshLambertMaterial" || materialType=="MeshPhongMaterial"){
        //     controls.emissive=_option.material[meshIndex].emissive.getStyle();
        // }
        if (materialType=="LineBasicMaterial"){
            controls.linewidth=_option.material[meshIndex].linewidth;
        }
        if (materialType=="MeshPhongMaterial"){
            controls.specular=_option.material[meshIndex].specular.getHex();
            controls.shininess=_option.material[meshIndex].shininess;
        }

        for (var i=0;i<gui.__controllers.length;i++){
            gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<objects_Gui.__controllers.length;i++){
            objects_Gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<generalMat_Gui.__controllers.length;i++){
            generalMat_Gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<BasicMat_Gui.__controllers.length;i++){
            BasicMat_Gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<DepthMat_Gui.__controllers.length;i++){
            DepthMat_Gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<NormalMat_Gui.__controllers.length;i++){
            NormalMat_Gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<LambertMat_Gui.__controllers.length;i++){
            LambertMat_Gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<PhongMat_Gui.__controllers.length;i++){
            PhongMat_Gui.__controllers[i].updateDisplay();
        }
        for (var i=0;i<LineBasicMat_Gui.__controllers.length;i++){
            LineBasicMat_Gui.__controllers[i].updateDisplay();
        }


        //更新光照参数
        for (var i=0;i<_option.light.length;i++){
            if (_option.light[i] instanceof THREE.AmbientLight){
                controls["ALVisable"]=_option.light[i].visible;
                controls["AmbientLightColor"]=_option.light[i].color.getStyle();
                controls["ALIntensity"]=_option.light[i].intensity;
                for (var j=0;j<AmbientLight_Gui.__controllers.length;j++){
                    AmbientLight_Gui.__controllers[j].updateDisplay();
                }
            }else if (_option.light[i] instanceof THREE.PointLight){
                controls["PLVisable"]=_option.light[i].visible;
                controls["SpotLightColor"]=_option.light[i].color.getStyle();
                controls["SLIntensity"]=_option.light[i].intensity;
                controls["SLPositionX"]=_option.light[i].position.x;
                controls["SLPositionY"]=_option.light[i].position.y;
                controls["SLPositionZ"]=_option.light[i].position.z;
                
                for (var j=0;j<PointLight_Gui.__controllers.length;j++){
                    PointLight_Gui.__controllers[j].updateDisplay();
                }
            }else if (_option.light[i] instanceof THREE.SpotLight){
                controls["PLVisible"]=_option.light[i].visible;
                controls["PointLightColor"]=_option.light[i].color.getStyle();
                controls["PLIntensity"]=_option.light[i].intensity;
                controls["PLPositionX"]=_option.light[i].position.x;
                controls["PLPositionY"]=_option.light[i].position.y;
                controls["PLPositionZ"]=_option.light[i].position.z;
                for (var j=0;j<SpotLight_Gui.__controllers.length;j++){
                    SpotLight_Gui.__controllers[j].updateDisplay();
                }
            }else if (_option.light[i] instanceof THREE.DirectionalLight){
                controls["DLVisable"]=_option.light[i].visible;
                controls["DLightColor"]=_option.light[i].color.getStyle();
                controls["DLIntensity"]=_option.light[i].intensity;
                controls["DLPositionX"]=_option.light[i].position.x;
                controls["DLPositionY"]=_option.light[i].position.y;
                controls["DLPositionZ"]=_option.light[i].position.z;
                for (var j=0;j<DirectionalLight_Gui.__controllers.length;j++){
                    DirectionalLight_Gui.__controllers[j].updateDisplay();
                }
            }else if (_option.light[i] instanceof THREE.HemisphereLight){
                controls["HLVisible"]=_option.light[i].visible;
                controls["HLColor"]=_option.light[i].color.getStyle();
                controls["HLGColor"]=_option.light[i].groundColor.getStyle();
                controls["HLIntensity"]=_option.light[i].intensity;
                for (var j=0;j<HemisphereLight_Gui.__controllers.length;j++){
                    HemisphereLight_Gui.__controllers[j].updateDisplay();
                }
            }

        }

        //更新雾化参数
        if (_option.scene.fog){
            controls.fogEnable=true;
            controls.fogColor=_option.scene.fog.color.getStyle();
            controls.fogNear=_option.scene.fog.near;
            controls.fogFar=_option.scene.fog.far;
        }else{
            controls.fogEnable=false;
            controls.fogColor=new THREE.Color(0xffffff).getStyle();
            controls.fogNear=50;
            controls.fogFar=500;
        }
        for (var i=0;i<scene_Gui.__controllers.length;i++){
            scene_Gui.__controllers[i].updateDisplay();
        }

        //背景色
        controls.rendererColor=_option.renderer.getClearColor().getStyle();
        for (var i=0;i<renderer_Gui.__controllers.length;i++){
            renderer_Gui.__controllers[i].updateDisplay();
        }


    }

    function loadJson(option,MatiralType) {

        if(MatiralType != undefined){
            urlMaterial = MatiralType;
        }
        $.ajaxSettings.async=false;
        for (var i=0;i<option.name.length;i++){

            var url= urlHead + urlMaterial + option.name[i] + ".json";
            $.getJSON(url,function (data,status) {
                if (status=="success"){
                    var loader = new THREE.ObjectLoader();
                    var loadedMesh = loader.parse(data);
                    option.material[i]=loadedMesh.material;

                    if(option.name[i]!="selecting"){  //selecting为拾取楼层时才有值
                        if(option.object[i] instanceof THREE.Group){
                            option.object[i].traverse(function (child) {
                                child.material=option.material[i];
                            });
                            console.log("成功导入 "+option.name[i]+"材质！");
                        }else if(option.object[i] instanceof THREE.Mesh){
                            option.object[i].material=option.material[i];
                            console.log("成功导入 "+option.name[i]+"材质！");
                        }else {
                            console.log("----------无法识别该对象----------")
                        }
                    }
                    
                    option.material[i].needsUpdate = true;

                }else {
                    console.log("----------初始化加载材质文件失败----------")
                    console.log(status);
                }
            });
        }

        //光照
        for (var i=0;i<option.light.length;i++){
            if (option.light[i] instanceof THREE.AmbientLight){
                var url= urlHead + urlMaterial + "AmbientLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        option.light[i].color.set(data.AmbientLightColor);
                        option.light[i].visible=data.visible;
                        option.light[i].intensity=data.intensity;
                        console.log("成功加载AmbientLight效果!");
                    }else {
                        console.log("----------初始化加载AmbientLight文件失败----------")
                        console.log(status);
                    }
                });
            }else if (option.light[i] instanceof THREE.PointLight){
                var url= urlHead + urlMaterial + "PointLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        option.light[i].color.set(data.color);
                        option.light[i].intensity=data.intensity;
                        option.light[i].visible=data.visable;
                        option.light[i].position.x=data.positionX;
                        option.light[i].position.y=data.positionY;
                        option.light[i].position.z=data.positionZ;
                        console.log("成功加载PointLight效果!");

                    }else {
                        console.log(status);
                    }
                });
            }else if (option.light[i] instanceof THREE.SpotLight){
                var url= urlHead + urlMaterial + "SpotLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        option.light[i].color.set(data.SpotLightColor);
                        option.light[i].intensity=data.intensity;
                        option.light[i].visible=data.SLVisable==undefined?true:data.SLVisable;
                        option.light[i].position.x=data.SLPositionX;
                        option.light[i].position.y=data.SLPositionY;
                        option.light[i].position.z=data.SLPositionZ;
                        console.log("成功加载SpotLight效果!");

                    }else {
                        console.log(status);
                    }
                });
            }else if (option.light[i] instanceof THREE.DirectionalLight){
                var url= urlHead + urlMaterial + "DirectionalLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        option.light[i].color.set(data.DLightColor);
                        option.light[i].intensity=data.intensity;
                        option.light[i].visible=data.DLVisible;
                        option.light[i].position.x=data.DLPositionX;
                        option.light[i].position.y=data.DLPositionY;
                        option.light[i].position.z=data.DLPositionZ;
                        console.log("成功加载DirectionalLight效果!");
                    }else {
                        console.log(status);
                    }
                });
            }else if (option.light[i] instanceof THREE.HemisphereLight){
                var url= urlHead + urlMaterial +"HemisphereLight.json";
                $.getJSON(url,function (data,status) {
                    if (status=="success"){
                        option.light[i].skyColor.set(data.color);
                        option.light[i].groundColor.set(data.groundColor);
                        option.light[i].visible=data.visible;
                        option.light[i].intensity=data.intensity;
                        console.log("成功加载HemisphereLight效果!");
                    }else {
                        console.log("----------初始化加载HemisphereLight文件失败----------")
                        console.log(status);
                    }
                });
            }
        }

        var sceneUrl= urlHead + urlMaterial +"sceneFog.json";
        $.getJSON(sceneUrl,function (data,status) {
            if (status=="success"){
                if (data.fogEnable){
                    option.scene.fog=new THREE.Fog(data.fogColor,data.fogNear,data.fogFar);
                }else {
                    option.scene.fog=null;
                }
                console.log("成功加载雾化效果!");
            }else {
                console.log(status);
            }
        });

        var rendererUrl= urlHead + urlMaterial +"rendererColor.json";
        $.getJSON(rendererUrl,function (data,status) {
            if (status=="success"){
                option.renderer.setClearColor(data.color);
                console.log("成功加载背景颜色!");

            }else {
                console.log(status);
            }
        });

        $.ajaxSettings.async=true;
        return option;
    }

    var link = document.createElement( 'a' );
    link.style.display = 'none';
    document.body.appendChild( link ); // Firefox workaround, see #6594

    function save( blob, filename ) {

        link.href = URL.createObjectURL( blob );
        link.download = filename;
        link.click();
    }

    function saveString( text, filename ) {

        save( new Blob( [ text ], { type: 'text/plain' } ), filename );

    }
}

